package com.health.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 登录过滤器
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest; // 向下转型
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        System.out.println("拦截请求");
        boolean filterFlag = false;
        if ((request.getSession().getAttribute("user")) != null) {
//            System.out.println("放行");
            filterFlag = true;
        } else {
//            System.out.println("执行拦截");
            response.sendRedirect(request.getContextPath() + "/pages/login.jsp");
        }
        if (filterFlag) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
